<?php
require_once("../include/func.php");
require_once("../include/conn.php");

$action = $_REQUEST['action'];
if (empty($action)) {
    $action = 'list';
}

echo "action is " . $action;

if ($action == 'new') {
    $content = $_POST['content'];
    $duration = $_POST['duration'];
    $expense = $_POST['expense'];
    $appear_after = $_POST['appear_after'];
    $priority = $_POST['priority'];

    $sql = "";
    if (empty($appear_after)) {
        $sql = sprintf("insert into todo(content,duration,expense,appear_after,priority, post_date) values('%s', %d, %.2f, null, %d, now())",
            $content, $duration, $expense, $priority);
    } else {
        $sql = sprintf("insert into todo(content,duration,expense,appear_after,priority, post_date) values('%s', %d, %.2f, '%s', %d, now())",
            $content, $duration, $expense, $appear_after, $priority);
    }

    echo "sql is " . $sql;
    $result = mysql_query($sql, $conn);


    mysql_close($conn);

    if (!$result) {
        echo "error create todo:" . mysql_error();
    } else {
        redirect('todo_list.php');
    }
} elseif ($action == 'mc') {
    $id = $_GET['id'];
    $sql = sprintf("update todo set status='complete', appear_after=null, complete_date=now() where id = %d", $id);

    $result = mysql_query($sql, $conn);
    mysql_close($conn);


} elseif ($action == 'del') {
    $id = $_GET['id'];
    $sql = sprintf("delete from todo where id = %d", $id);

    $result = mysql_query($sql, $conn);
    mysql_close($conn);


} elseif ($action == 'mod') {
    $id = $_POST['id'];
    $content = $_POST['content'];
    $duration = $_POST['duration'];
    $expense = $_POST['expense'];
    $appear_after = $_POST['appear_after'];
    $priority = $_POST['priority'];
    $sql = sprintf("update todo set content = '%s', duration=%d, expense=%.2f, appear_after='%s', priority=%d where id = %d",
        $content, $duration, $expense, $appear_after, $priority, $id);
    echo "sql:" . $sql;

    $result = mysql_query($sql, $conn);
    mysql_close($conn);

    if (!$result) {
        echo "error update todo:" . mysql_error();
    } else {
        redirect('todo_list.php');
    }

}


